<template>
  <div class="viewcontainer">
    <el-dialog
      :title="detailTitle"
      :visible.sync="detailFormVisible"
      width="500px"
      :close-on-click-modal="false"
      @close="clickClose"
    >
      <hi-form
        ref="detailForm"
        v-if="detailFormVisible"
        :model="editData"
        :rules="rules"
        v-bind="form"
        :items="formItem"
      ></hi-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="save" :loading="saving"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-row class="view-header">
      <el-col :span="22">
        <hi-lquery
          :columnsTotal="3"
          v-bind="queryPanel"
          @afterquery="afterquery"
        ></hi-lquery>
      </el-col>
      <el-col :span="2" style="text-align: right">
        <el-button type="primary" @click="showAdd">添加</el-button>
      </el-col>
    </el-row>
    <el-row class="view-main">
      <el-table
        ref="dataTable"
        :data="userData"
        height="100%"
        style="width: 100%"
        v-loading=""
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="fuserid" label="工号" width="180" />
        <el-table-column prop="fusernameid" label="姓名" width="180" />
        <el-table-column prop="fmbphone" label="手机号码" width="180" />
        <el-table-column prop="frolename" label="岗位" width="180" />
        <el-table-column prop="forgname" label="部门" />
        <el-table-column prop="fstate" label="禁用标识" width="140">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.fstate" type="danger">已禁用</el-tag>
            <div v-else></div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="80">
          <template slot-scope="scope">
            <el-button
              title="编辑"
              v-if="!scope.row.fstate"
              type="text"
              size="small"
              @click="showEdit(scope.row)"
            >
              <i class="el-icon-edit"></i>
            </el-button>
            <el-button
              title="禁用"
              v-if="!scope.row.fstate"
              type="text"
              size="small"
              @click="remove(scope.row)"
            >
              <i class="el-icon-remove-outline"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="view-footer pagebar">
      <hi-pagination
        :page-size="pageSize"
        :current-page.sync="pageIndex"
        @current-change="currentChange"
        background
        :total="total"
      ></hi-pagination>
    </el-row>
  </div>
</template>

<script>
import { HiPagination, HiLquery, HiVquery, HiForm } from "hi-ui";
import { dataHelper } from "hi-ui";
import viewBase from "@/views/base";
import user from "@/api/user";
import store from "@/store";
import { utils } from "hi-ui";
import bind from "lodash/bind";
export default {
  name: "staffList",
  extends: viewBase,
  components: { HiPagination, HiLquery, HiVquery, HiForm },
  data() {
    var validatePass = (rule, value, callback) => {
      if (value !== this.editData.fpasswordTemp) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };

    return {
      userData: [
        /*   {
          fuserid: "2016-05-02",
          fusernameid: "王小虎",
          fmbphone: "12345676855",
          femail: "123@qq.com",
          fqq: "121323",
          fweixin: "12345",
        }, */
      ],
      //数据桥梁
      dataBridge: new Map(),
      saving: false,
      detailTitle: null,
      //编辑状态
      editstate: "add",
      editData: {},
      oldData: {},
      total: 9999,
      pageSize: 20,
      pageIndex: 1,
      queryParam: {},
      detailFormVisible: false,
      defRawPwd: "****",
      //表单配置
      form: {
        columnsTotal: 1,
      },
      rules: {
        frepassword: [{ validator: validatePass, trigger: "blur" }],
      },

      //查询面板配置
      queryPanel: {
        fields: [
          {
            element: "el-input",
            label: "工号",
            name: "fuserid",
          },
          {
            element: "el-input",
            label: "姓名",
            name: "fusernameid",
          },
          {
            element: "el-input",
            label: "手机号码",
            name: "fmbphone",
          },
        ],
      },
    };
  },
  model: {
    prop: "value",
    event: "valuechange",
  },
  props: {
    value: {
      type: Object,
    },
  },

  computed: {
    formItem() {
      return [
        {
          name: "fuserid",
          element: "el-input",
          label: "工号",
          required: true,
          props: {},
        },
        {
          name: "fusernameid",
          element: "el-input",
          label: "姓名",
          required: true,
        },
        {
          name: "fpasswordTemp",
          element: "el-input",
          label: "密码",
          hide: false, //this.editstate != "add",
          required: true,
          props: {
            "show-password": true,
          },
        },
        {
          name: "frepassword",
          element: "el-input",
          label: "确认密码",
          hide: false, //this.editstate != "add",
          required: true,
          props: {
            "show-password": true,
          },
        },

        {
          name: "frolename",
          element: "hi-select-grid",
          label: "岗位",
          required: true,
          props: {
            selectOption: {
              loading: true,
              multiple: false,
              clearable: true,
              filterable: true,
              "allow-create": true,
              "collapse-tags": true,
            },
            lookup: {
              modelFile: "xtgl/dataset/SysRoleBizEntity.xml",
              label: "frolename",
              // param: new dataHelper.queryHelper.Param(
              //   new dataHelper.queryHelper.Where({
              //     join: "and",
              //     criterionData: {
              //       items: [
              //         {
              //           sign: "eq",
              //           name: "frolepguid",
              //           tablefilter: false,
              //           dataType: "dbString",
              //           value: "-1",
              //           enabled: true,
              //         },
              //       ],
              //     },
              //   })
              // ),
              param: new dataHelper.queryHelper.Param({
                where: new dataHelper.queryHelper.Where({
                  join: "and",
                  criterionData: {
                    items: [
                      {
                        sign: "noteq",
                        name: "frolepguid",
                        tablefilter: false,
                        dataType: "dbString",
                        value: "-1",
                        enabled: true,
                      },
                    ],
                  },
                }),
              }),
              tableprops: {
                "show-header": false,
                "max-height": 400,
              },
              returnFields: {
                froleid: "froleid",
                frolename: "frolename",
                froleguid: "froleguid",
              },
              columns: [
                {
                  name: "frolename",
                  label: "名称",
                },
              ],
            },
          },
        },

        {
          name: "forgid",
          element: "hi-cascader",
          label: "部门",
          required: true,
          props: {
            lookup: {
              modelFile: "xtgl/dataset/SysOrgBizEntity.xml",
              param: { $pageIndex: -1, $pageSize: -1 },
              id: "forgguid",
              pid: "forgpguid",
              label: "forgname",
              //pathLabels: "forgname", //标签路径
              returnFields: {
                forgid: "forgid",
                forgname: "forgname",
                forgguid: "forgguid",
              },
            },

            "show-all-levels": false,
            props: {
              value: "forgid",
              label: "forgname",
              leaf: "isleaf",
              lazy: true,
              emitPath: false,
              //checkStrictly: true
            },
          },
        },

        {
          name: "fmbphone",
          element: "el-input",
          label: "手机号码",
          required: true,
        },
        {
          name: "femail",
          element: "el-input",
          label: "邮箱",
        },
        {
          name: "fqq",
          element: "el-input",
          label: "qq帐号",
        },
        {
          name: "fweixin",
          element: "el-input",
          label: "微信帐号",
        },
      ];
    },
  },
  watch: {},
  methods: {
    //对话框关闭
    clickClose() {
      this.formItem.forEach((element) => {
        if (element.name == "fuserid") {
          element.props = {};
        }
        if (element.name == "fpasswordTemp") {
          element.hide = false;
        }
        if (element.name == "frepassword") {
          element.hide = false;
        }
      });
    },
    //分页事件
    currentChange(pageNum) {
      this.query(this.queryParam);
    },
    //查询事件
    afterquery(queryPanel, param) {
      this.queryParam = param;
      this.pageIndex = 1;
      this.query(param, 1);
    },
    query() {
      this.queryEntity(this.queryParam, "xtgl/dataset/UserQuery.xml", null, {
        extParam: {
          pageNum: this.pageIndex,
          pageSize: this.pageSize,
          __returnCount: true,
        },
      }).then((res) => {
        this.userData = res.dataPack.rows;
        this.total = res.outParameter.factRecordSize; //返回总数据
      });
      // user.queryUser(this.queryParam, this.pageIndex, this.pageSize).then((res) => {
      //   this.userData = res.dataPack.rows;
      // });
    },
    createEmptyData() {
      let data = {
        femail: null,
        fmbphone: null,
        fpasswordTemp: null,
        frepassword: null,
        fqq: null,
        fsecondpwd: null,
        fthirdpwd: null,
        fuserid: null,
        fusernameid: null,
        fweixin: null,
        froleid: null, // store.getters.userInfo.org[1].froleid,
        frolename: null,
        forgid: null, //store.getters.userInfo.org[1].forgid,
        forgname: null,
        forgguid: null, //企业orgguid
        froleguid: null, //机构froleguid
      };

      return data;
    },
    showAdd() {
      this.editstate = "add";
      this.detailTitle = "添加工号";
      this.editData = this.createEmptyData();
      this.detailFormVisible = true;
    },
    showEdit(data) {
      debugger;
      this.formItem.forEach((element) => {
        if (element.name == "fuserid") {
          element.props.disabled = true;
        }
        if (element.name == "fpasswordTemp") {
          element.hide = true;
        }
        if (element.name == "frepassword") {
          element.hide = true;
        }
      });
      var data1 = {};
      if (!data["frolename"]) {
        data1.frolename = null;
      }
      if (!data["forgname"]) {
        data1.forgname = null;
      }
      if (!data["forgid"]) {
        data1.forgid = null;
      }
      if (!data["fweixin"]) {
        data1.fweixin = null;
      }
      if (!data["fqq"]) {
        data1.fqq = null;
      }
      if (!data["femail"]) {
        data1.femail = null;
      }
      this.editData = Object.assign(data1, data);
      this.oldData = Object.assign({}, data);

      this.editstate = "edit";
      // this.editData.forgid = [this.editData.forgid]
      this.editData.fpasswordTemp = this.editData.frepassword = this.defRawPwd;
      this.detailTitle = "编辑" + this.editData.fuserid || "";
      this.detailFormVisible = true;
    },
    //改成禁用接口
    remove(data) {
      this.$confirm("确定要禁用【" + data.fuserid + "】", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        // let id = [];
        // id.push(data.fuserid);
        user
          .disabledUser({
            userId: data.fuserid,
          })
          .then((res) => {
            this.query();
            this.$message({
              type: "success",
              message: "禁用成功!",
            });
          });
      });
    },
    save() {
      let _result;
      this.$refs.detailForm.validate((result) => {
        _result = result;
      });
      if (!_result) return;
      let saveHelper = this.createSaveHelper();
      let saveData = Object.assign({}, this.editData);
      if (this.editstate == "edit") {
        // if (this.defRawPwd != saveData.fpasswordTemp) {
        saveData.fpassword = utils.string.md5(saveData.fpasswordTemp);
        // }

        delete saveData.fpasswordTemp;
        delete saveData.frepassword;
        saveData.fpassword;

        saveHelper.add(saveData);
        let dataPack = saveHelper.getDataPack();
        this.saving = true;
        user
          .updateUser({
            fuserid: dataPack.data[0].fuserid,
            fusername: dataPack.data[0].fusernameid,
            fmbphone: dataPack.data[0].fmbphone,
            fpassword: dataPack.data[0].fpassword,
            forgguid: dataPack.data[0].forgguid || "", //部门
            froleguid: dataPack.data[0].froleguid || "", //岗位
            foldroleguid: this.oldData.froleguid || "", //旧岗位
            foldorgguid: this.oldData.forgguid || "", //旧部门
            femail: dataPack.data[0].femail,
            fqq: dataPack.data[0].fqq,
            fweixin: dataPack.data[0].fweixin,
          })
          .then((res) => {
            this.$message({
              message: "保存成功",
              type: "success",
            });
            this.detailFormVisible = false;
            this.saving = false;
            this.query();
          })
          .catch((res) => {
            this.saving = false;
            console.error(res);
          });
      } else {
        saveData.fpassword = utils.string.md5(saveData.fpasswordTemp);
        delete saveData.fpasswordTemp;
        delete saveData.frepassword;
        saveHelper.add(saveData);
        let dataPack = saveHelper.getDataPack();
        this.saving = true;
        user
          .saveUser({
            fuserid: dataPack.data[0].fuserid,
            fusername: dataPack.data[0].fusernameid,
            fmbphone: dataPack.data[0].fmbphone,
            fpassword: dataPack.data[0].fpassword,
            forgguid: dataPack.data[0].forgguid, //部门
            froleguid: dataPack.data[0].froleguid, //岗位
            femail: dataPack.data[0].femail,
            fqq: dataPack.data[0].fqq,
            fweixin: dataPack.data[0].fweixin,
          })
          .then((res) => {
            this.$message({
              message: "保存成功",
              type: "success",
            });
            this.detailFormVisible = false;
            this.saving = false;
            this.query();
          })
          .catch((res) => {
            this.saving = false;
            console.error(res);
          });
      }
    },
  },
  mounted() {
    this.query();
    //this.dataset = this.$dsContainer.createDataSet(this.datasetCfg);
    //this.dataBridge.set(this.dataset, ["dataTable", "detailForm"]);
    // this.test();
  },
};
</script>
<style rel="stylesheet/scss" lang="scss" scope></style>
